package com.lysj.bhp.util.signature;

import com.lysj.bhp.manager.base.ManagerInterceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.util.Map;

public class SignatureUtil {

    private static final  Logger logger = LoggerFactory.getLogger(SignatureUtil.class);

    /**
     * 对一个参数列表签名
     *
     * @param paramMap,参数列表
     * @param keyName,签名秘钥参数名
     * @param key,签名秘钥
     */
    public static void paramSign(Map<String, Object> paramMap, String keyName, String key) {
        StringBuilder paramBuilder = new StringBuilder();
        paramMap.forEach((k, v) -> paramBuilder.append(k).append("=").append(v).append("&"));
        if (!"".equals(keyName)) {// 在参数后附带上签名秘钥
            paramBuilder.append(keyName).append("=").append(key);
        }
        String paramStr = paramBuilder.toString();
        logger.debug("signature param string -> " + paramStr);
        String paramSignature = SignatureUtil.md5(paramStr);
        logger.debug("signature result string -> " + paramSignature);
        paramMap.put("signature", paramSignature);

    }


    // 将map转化为字符串参数
    public static String map2param(Map<String, String> paramMap) {
        StringBuilder paramBuilder = new StringBuilder();
        paramMap.forEach((k, v) -> {
            paramBuilder.append(k).append("=").append(v).append("&");
        });

        return paramBuilder.substring(0, paramBuilder.length() - 1);
    }


    /**
     * 获取一个字符串的md5值,编码为utf-8
     *
     * @param string
     * @return 32位MD5摘要过后的字符串
     */
    public static String md5(String string) {
        if (string == null || string.trim().equals("")) {
            return null;
        }
        try {
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] data = digest.digest(string.getBytes("utf-8"));
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < data.length; i++) {
                String result = Integer.toHexString(data[i] & 0xff);
                String temp = null;
                if (result.length() == 1) {
                    temp = "0" + result;
                } else {
                    temp = result;
                }
                sb.append(temp);
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
